package com.wenjiang.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.Callback;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Date;

@Component
public class OSSUtils {

    @Autowired
    OSS ossClient;

    @Value("${oss.bucketName}")
    String bucketName;


    //上传文件

    /**
     *
     * @param bytes  字节数组
     * @param ossName  对象名称（文件名称）
     */
    public void upload(byte[] bytes,String ossName){

        ossClient.putObject(bucketName,ossName,new ByteArrayInputStream(bytes));

    }


    //上传文件 （回调url）

    public  PutObjectResult  uploadCallBack(byte[] bytes, String ossName, Callback callback){
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, ossName,
                new ByteArrayInputStream(bytes));

        putObjectRequest.setCallback(callback);

        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

        return putObjectResult;
    }

    /**
     *
     * @param path 根据文件路径进行删除
     */
    //删除某个文件
    public void  delFile(String path){
          ossClient.deleteObject(bucketName,path);
    }


    //生成文件的url

    /**
     *
     * @param path 文件的完整路径
     * @return
     */

    public  String getUrl(String path){
        // 设置十年的过期时间
        Date date= new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        URL url = ossClient.generatePresignedUrl(bucketName, path, date);

      return    url.toString();

    }


}
